package com.sanji.sjmallmodule.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.sanji.sjmallapp.MallApplication;
import com.sanji.sjmallapp.R;
import com.sanji.sjmallconfig.ConfigAPI;
import com.sanji.sjmallconfig.ConfigConts;
import com.sanji.sjmallmanager.http.NoHttpCallBack;
import com.sanji.sjmallmanager.http.NoHttpListener;
import com.sanji.sjmallmodule.goods.BaseFrament;
import com.sanji.sjmallmodule.goods.GoodsDetailsActivity;
import com.sanji.sjmallutils.SharePreferenceUtil;
import com.sanji.sjmallutils.Tools;
import com.sanji.sjmallwidget.XListView;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.sanji.sjmallapp.MallApplication.myShare;

/**
 * 我的订单--页签
 * Created by zsf on 17-1-12.
 */
public class MyOrderFragment extends BaseFrament implements AdapterView.OnItemClickListener, NoHttpListener, XListView.IXListViewListener, MyOrderListAdapter.CancelOrderListener, MyOrderListAdapter.BuyAgainOrderListener, MyOrderListAdapter.PayOrderListener {
    //标志位 标志已经初始化完成
    private boolean isPrepared;

    @BindView(R.id.my_order_viewpager_listview)
    XListView mMyOrderViewpagerListview;
    private int pageIndex = 0;

    private List<MyOrderBean> allList = new ArrayList<>();
    private List<MyOrderBean> mDataList;

    private MyOrderListAdapter allListAdapter;
    MyOrderBean order;
    MyOrderBean cancelOrder;
    String orderUrl;
    String cancelUrl;
    String userId;
    private SharePreferenceUtil sp;
    private Request<JSONObject> request;
    private int page = 1;//页数
    private boolean pagerCanloder = false;
    private boolean refresh = false;
    private String userName;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.viewpager_my_order, null);
        ButterKnife.bind(this, view);
        isPrepared = true;
        initView();
        lazyLoadData();
        return view;
    }

    public void initView() {
        sp = MallApplication.getApplication().myShare;
        userId = sp.getString(ConfigConts.USER_ID, null);
        userName = sp.getString(ConfigConts.TRUE_NAME, null);
        mDataList = new ArrayList<>();
        mMyOrderViewpagerListview.setPullLoadEnable(false);
        mMyOrderViewpagerListview.setHeaderDividersEnabled(false);
        mMyOrderViewpagerListview.setFooterDividersEnabled(false);
        mMyOrderViewpagerListview.setXListViewListener(this);

        allListAdapter = new MyOrderListAdapter(getActivity(), allList);
        mMyOrderViewpagerListview.setAdapter(allListAdapter);

        allListAdapter.setBuyAgainOrderListener(this);
        allListAdapter.setCancelOrderListener(this);
        allListAdapter.setPayOrderListener(this);

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (i > 0) {
            order = allList.get(i - 1);
            Intent intent = new Intent(getActivity(), MyOrderDestActivity.class);
            intent.putExtra("order", order);
            startActivityForResult(intent, 110);
        }
    }

    @Override
    public void lazyLoadData() {
        if (!isPrepared || !isVisible) {
            return;
        }
        pageIndex = this.getArguments().getInt("pages");
        boolean refres = MallApplication.getApplication().getRefreshMap().get(pageIndex);
        if (allList.size() == 0) {
            //未支付网络请求
            requestOrder();
        } else if (refres) {
            onRefresh();
            MallApplication.getApplication().getRefreshMap().put(pageIndex, false);
        } else {
            allListAdapter.notifyData(allList);
        }
        mMyOrderViewpagerListview.setOnItemClickListener(this);
    }

    /**
     * 网络请求订单
     */
    public void requestOrder() {
        getUrl(pageIndex);
        request = NoHttp.createJsonObjectRequest(orderUrl, RequestMethod.GET);
        request.setCancelSign(orderUrl.hashCode());
        NoHttpCallBack.getInstance().add(getActivity(), orderUrl.hashCode(), request, this, true, true);
    }


    /**
     * 获取url
     */
    public void getUrl(int index) {
        switch (index) {
            case 0:
                //全部订单
                orderUrl = ConfigAPI.MY_ORDER_URL + "memberId=" + userId + "&page=" + page;
                break;
            case 1:
                //待付款
                orderUrl = ConfigAPI.MY_ORDER_URL + "memberId=" + userId + "&page=" + page + "&payStatus=0";
                break;
            case 2:
                //待发货
                orderUrl = ConfigAPI.MY_ORDER_URL + "memberId=" + userId + "&page=" + page + "&shipStatus=0";
                break;
            case 3:
                //已付款
                orderUrl = ConfigAPI.MY_ORDER_URL + "memberId=" + userId + "&page=" + page + "&payStatus=1";
                break;
        }
    }

    @Override
    public void onSuccessed(int what, Response response) {
        JSONObject json = (JSONObject) response.get();
        String status = json.optString(ConfigConts.STATUS_STRING);
        if (what == orderUrl.hashCode()) {
            if (status.equals(ConfigConts.STATUS_SUCCESS)) {
                JSONObject object = json.optJSONObject("result");
                JSONArray content = object.optJSONArray("orders");
                int totalPages = object.optInt("totalPage");
                if (totalPages > page) {
                    pagerCanloder = true;
                } else {
                    pagerCanloder = false;
                }
                mMyOrderViewpagerListview.setPullLoadEnable(pagerCanloder);
                if (refresh) {
                    allList.clear();
                    refresh = false;
                }
                for (int i = 0; i < content.length(); i++) {
                    MyOrderBean orderBean = new MyOrderBean();
                    JSONObject order = content.optJSONObject(i);
                    String orderNum = order.optString("orderNum");//订单号
                    String orderId = order.optString("orderId");
                    Long createTime = order.optLong("createTime");//创建时间
                    String type = order.optString("type");//商品类型

                    Long payTime = order.optLong("payTime");//付款时间
                    Long shipTime = order.optLong("shipTime");//发货时间
                    int orderPoints = order.optInt("orderPoints");//积分

                    int shipStatus = order.optInt("shipStatus");//发货状态

                    int payStatus = order.optInt("payStatus");//订单付款状态
//                    String receiverName = order.optString("username");//收货人
                    int orderStatus = order.optInt("orderStatus");//订单状态
                    int payMent = order.optInt("payMent");//付款方式
                    Double fare = order.optDouble("count");//运费
                    Double transportMoney = order.optDouble("transportMoney");//合计
                    JSONArray goods = order.optJSONArray("goods");//商品列表
                    List<ShopcarChildBean> goodsList = new ArrayList<>();
                    if (goods != null && goods.length() > 0) {
                        for (int j = 0; j < goods.length(); j++) {
                            JSONObject goodsObject = goods.optJSONObject(j);
                            String name = goodsObject.optString("name");
                            String imgUrl = goodsObject.optString("imgUrl");//商品的图片
                            String targetType = goodsObject.optString("type");//商品类型,sku ： 手机， gift ： 赠品， accessories ： 配件
                            //商品解析edition，赠品解析color
                            String edition = goodsObject.optString("edition");//商品规格和颜色
                            String color = goodsObject.optString("color");
                            String goodsNum = goodsObject.optString("goodsNum");//商品编号
                            String skuId = goodsObject.optString("skuNum");//sku编码
                            int num = goodsObject.optInt("goodsCount");//商品的数量
                            double price = goodsObject.optDouble("price");//价格
                            ShopcarChildBean goodsChild = new ShopcarChildBean();
                            goodsChild.setImgUrl(imgUrl);
                            goodsChild.setGoodsName(name);
                            goodsChild.setGoodsType(targetType);
                            goodsChild.setGoodsId(goodsNum);
                            goodsChild.setGoodsCount(num);
                            goodsChild.setColor(color);
                            goodsChild.setGoodsSpec(edition);
                            goodsChild.setGoodsPrice(price);
                            goodsChild.setSkuId(skuId);
                            goodsList.add(goodsChild);
                        }
                    }
                    orderBean.setOrderNo(orderNum);
                    orderBean.setOrderId(orderId);
                    orderBean.setBuyDate(Tools.paseToDate(createTime));
                    orderBean.setAmount(transportMoney);
                    orderBean.setReceiverName(userName);
                    orderBean.setFare(fare);
                    orderBean.setGoodsList(goodsList);

                    orderBean.setPaidDate(payTime == 0 ? getResources().getString(R.string.order_no_pay) : Tools.paseToDate(payTime));//付款时间
                    orderBean.setPayStatus(payStatus);
                    orderBean.setPaidType(payMent);
                    orderBean.setFareDate(shipTime == 0 ? getResources().getString(R.string.order_no_ship) : Tools.paseToDate(shipTime));//发货时间
                    orderBean.setShipStatus(shipStatus);
                    orderBean.setPoint(orderPoints);
                    orderBean.setOrderStatus(orderStatus);
                    //
                    allList.add(orderBean);
                }
                allListAdapter.notifyData(allList);
            }
        } else if (what == cancelUrl.hashCode()) {
            String statusS = json.optString(ConfigConts.STATUS_STRING);
            if (statusS.equals(ConfigConts.STATUS_SUCCESS)) {
                String sucessMsg=json.optString(ConfigConts.SUCCESSMSG);
                Tools.toastTools(getActivity(), sucessMsg);
                allList.remove(cancelOrder);
                allListAdapter.notifyData(allList);
            } else if (statusS.equals(ConfigConts.STATUS_ERROR)) {
                String errorMsg = json.optString(ConfigConts.ERRORMSG);
                Tools.toastTools(getActivity(), errorMsg);
            }
        }
        mMyOrderViewpagerListview.stopRefresh();
        mMyOrderViewpagerListview.stopLoadMore();
    }

    @Override
    public void onFailed(int what, Response response) {
        Tools.toastTools(getActivity(), getResources().getString(R.string.request_time_out));
    }

    @Override
    public void onRefresh() {
        //刷新
        refresh = true;
        page = 1;
        getUrl(pageIndex);
        requestOrder();
    }

    @Override
    public void onLoadMore() {
        //加载更多
        if (pagerCanloder) {
            page++;
            getUrl(pageIndex);
            requestOrder();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != request) {
            request.cancel();
        }
    }

    /**
     * @param orderBean 再次购买
     */
    @Override
    public void buyAgainOrder(MyOrderBean orderBean) {
        Intent intent = new Intent(getActivity(), GoodsDetailsActivity.class);
        List<ShopcarChildBean> goodList = orderBean.getGoodsList();
        ShopcarChildBean shopcarChildBean = new ShopcarChildBean();
        for (int i = 0; i < goodList.size(); i++) {
            shopcarChildBean = goodList.get(i);
            if (shopcarChildBean.getGoodsType().equals("")) {
                intent.putExtra("goodsCode", orderBean.getAmount());
                return;
            }

        }
        startActivity(intent);
    }

    /**
     * @param orderBean 取消购买
     */
    @Override
    public void cancelOrder(MyOrderBean orderBean) {
        cancelOrder = orderBean;
        cancelUrl = ConfigAPI.MY_ORDER_CANCEL_URL + "?orderId=" + cancelOrder.getOrderId() + "&reason=" + "";
        request = NoHttp.createJsonObjectRequest(cancelUrl, RequestMethod.POST);
        request.setCancelSign(cancelUrl.hashCode());
        NoHttpCallBack.getInstance().add(getActivity(), cancelUrl.hashCode(), request, this, true, true);
    }

    /**
     * @param orderBean 立即支付
     */
    @Override
    public void payOrder(MyOrderBean orderBean) {
        Intent intent = new Intent(getActivity(), OrderPayActivity.class);
        intent.putExtra("actualAmount", orderBean.getAmount());
        intent.putExtra("orderId", orderBean.getOrderId());
        startActivityForResult(intent, 110);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == getActivity().RESULT_OK && requestCode == 110) {
            onRefresh();
            Map<Integer, Boolean> map = MallApplication.getApplication().getRefreshMap();
            for (int i = 0; i < map.size(); i++) {
                map.put(i, true);
            }
            map.put(pageIndex, false);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
